﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using org.pdfbox.pdmodel;
using org.pdfbox.pdmodel.common;
using org.pdfbox.util;
using org.apache.lucene.document;
using Rcornejo.Text;

namespace PdfLucene
{
    public class PDFManager
    {
        //private PDDocument tempDocument;
    
        public static void GetFileInfo()
        {
            throw new System.NotImplementedException();
        }

        public static List<PDFFile> GetFilesInfo(string[] files)
        {
            List<PDFFile> pdfFiles = null;
            FileInfo fileInfo = null;
            try
            {
                pdfFiles = new List<PDFFile>();
                if (files != null)
                {
                    foreach (string file in files)
                    {
                        fileInfo = new FileInfo(file);
                        pdfFiles.Add(GetFileContents(fileInfo));
                    }
                }

            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message + fileInfo.FullName);
            }
            finally
            {

            }
            return pdfFiles;
        }

        public static PDFFile GetFileContents(FileInfo fileInfo)
        {
            PDDocument tempDocument = null;
            PDFFile pdfFile = null;
            PDFTextStripper pdfStripper = null;
            PDDocumentInformation tempDocumentInfo = null;
            string contents = string.Empty;
            try
            {
                pdfStripper = new PDFTextStripper();
                pdfFile = new PDFFile();
                tempDocument = PDDocument.load(fileInfo.FullName);
                tempDocumentInfo = tempDocument.getDocumentInformation();
                //Gets content
                pdfFile.Contents = pdfStripper.getText(tempDocument);
                //Gets title
                pdfFile.Title = tempDocumentInfo.getTitle();
                //Gets Keywords
                pdfFile.Keywords = tempDocumentInfo.getKeywords();
                //Gets Modified Time
                pdfFile.ModifiedTime = DateTools.timeToString(tempDocumentInfo.getModificationDate().getTimeInMillis(),DateTools.Resolution.MINUTE);
                //Gets Path
                pdfFile.Path = fileInfo.FullName;
                //Gets Abstract
                //TODO: get abstract
                pdfFile.Abstract = ParseAbstract(pdfFile.Contents);
                Console.WriteLine(pdfFile.Path);
                Console.Write(pdfFile.Abstract);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + fileInfo.FullName);
            }
            finally
            {
                tempDocument.close();
               // pdfStripper = null;
            }
            
            return pdfFile;
        }
        private static string ParseAbstract(string contents)
        {
            StringTokenizer tokenizer = new StringTokenizer(contents);
            tokenizer.IgnoreWhiteSpace = true;
            Token token = null;
            string _abstract = string.Empty;
            short words=0;
            do
            {
                token = tokenizer.Next();
                words += 1;
                if (token.Value.ToLower().Equals("abstract"))
                {
                    words = 0;
                    do
                    {
                        token = tokenizer.Next();
                        words += 1;
                        _abstract += token.Value + " ";
                        if (words == 299)
                        {
                            _abstract += "fin";
                        }
                    } while (words <= 300);//tokenKind!=TokenKind.EOF);
                }              
            } while (token.Kind!= TokenKind.EOF && words<=300);
            return _abstract;
        }
        private static string ParseTitle(string contents)
        {
            StringTokenizer tokenizer = new StringTokenizer(contents);
            tokenizer.IgnoreWhiteSpace = true;
            Token token = null;
            TokenKind tokenKind = TokenKind.Unknown;
            string title = string.Empty;
            do
            {
                token = tokenizer.Next();
                if (token.Kind.Equals(TokenKind.EOL))//TODO: check abstracts lenght in templates
                    tokenKind = TokenKind.EOF;
                else
                    title += token.Value + " ";
            } while (tokenKind != TokenKind.EOF && token.Kind != TokenKind.EOF);
            return title;
        }
        private static string ConvertStreamToString(java.io.InputStream stream)
        {
            if (stream != null)
            {
                StringBuilder sb = new StringBuilder();
                String line;
               try {
                   java.io.BufferedReader reader = new java.io.BufferedReader(new java.io.InputStreamReader(stream, "UTF-8"));
                    while ((line = reader.readLine()) != null) {
                        sb.Append(line).Append("\n");
                    }
                }
               finally {
                    stream.close();
               }
                return sb.ToString();
            }
            else {       
                return "";
            }
        }
    }
}
